package com.squirrels.server.work;

import com.squirrels.server.annotation.NettyServerWorker;
import com.squirrels.server.common.constant.SystemConstant;
import com.squirrels.server.common.constant.UserConstant;
import com.squirrels.server.message.Login;
import com.squirrels.server.message.protobuf.Message;
import com.squirrels.server.service.UserService;
import com.squirrels.server.utils.EntityUtils;
import com.squirrels.server.utils.JWTUtils;
import dev.morphia.Datastore;
import dev.morphia.query.MorphiaCursor;
import dev.morphia.query.Query;
import dev.morphia.query.filters.Filters;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;

/**
 * 创建者: FlyingSquirrels
 * 创建时间: 2024/7/30 10:48
 * 描述: 登录功能
 */
@Slf4j
@NettyServerWorker("login")
public class LoginWorker extends ServerWorker{

    private static UserService userService;

    /**
     * 为当前类注入service
     * @param datastore
     */
    private void doService(Datastore datastore) {
        userService = UserService.operation(datastore);
    }

    @Override
    public Message.Entity doWorker(String operationBase) {
        // 注入 Service
        doService(datastore);
        Message.Entity responseData;
        // 根据请求头部执行操作
        switch (operationBase){
            // 登录
            case "login" -> {
                responseData = valid(entity);
            }
            // 注册
            case "register" -> {
                responseData = create(entity);
            }
            // 重置
            case "forget" -> {
                responseData = forget(entity);
            }
            // 注册
            case "test" -> {
                responseData = test(entity);
            }
            default -> {
                responseData = errorMsg(UserConstant.OPERATION_NOT_ERROR,entity);
            }
        }
        return responseData;
    }

    /**
     * 重置密码
     * @param entity
     * @return
     */
    private Message.Entity forget(Message.Entity entity) {
        Login login = Login.fromEntity(entity);
        if (Login.accountIsNotNull(login)) {
            boolean isReset = userService.resetPassword(login.getUsername(),login.getPassword());
            Message.Entity out;
            if (isReset){
               out = EntityUtils.buildResData(entity, UserConstant.RESET_OK, null);
            }else{
                out = errorMsg(UserConstant.EMPTY_ERROR,entity);
            }
            return out;
        }
        return errorMsg(UserConstant.PARAM_ERROR,entity);
    }

    /**
     * 注册用户
     * @param entity
     * @return
     */
    private Message.Entity create(Message.Entity entity) {
        Login login = Login.fromEntity(entity);
        if (Login.accountIsNotNull(login)) {
            boolean isExists = userService.searchByName(login.getUsername());
            if (isExists){
                return errorMsg(UserConstant.ALREADY_ERROR,entity);
            }
            datastore.insert(login);
            Message.Entity out = EntityUtils.buildResData(entity, SystemConstant.OK, null);
            return out;
        }
        return errorMsg(UserConstant.PARAM_ERROR,entity);
    }

    /**
     * 验证账号密码
     *
     * @param entity
     * @return
     */
    private Message.Entity valid(Message.Entity entity) {
        Login login = Login.fromEntity(entity);
        if (!Login.accountIsNotNull(login)) {
            return errorMsg(UserConstant.PARAM_ERROR,entity);
        }
        Login data = userService.login(login);
        if (null == data) {
            return errorMsg(UserConstant.EMPTY_ERROR,entity);
        }
        String token = JWTUtils.jwtUtils.getJwtToken(data.getId().toString());
        Message.Entity out = EntityUtils.buildResData(entity, SystemConstant.OK, null, token);
        return out;
    }

    /**
     * 验证账号密码
     *
     * @param entity
     * @return
     */
    private Message.Entity test(Message.Entity entity) {
        System.out.println(entity);
        int i = 0;
        for (i = 0; i < 5 ; i++){
            Message.Data data = Message.Data.newBuilder().setInfo("开始传输数据" + i).build();
            Message.Entity build = Message.Entity.newBuilder().setData(data).build();
            DatagramPacket datagramPacket = new DatagramPacket(ctx.alloc().buffer().writeBytes(build.toByteArray()),sender);
            ctx.write(datagramPacket);
        }
        return entity;
    }

}
